<template>
    <div class="cmt-container">
        <h2>发表评论</h2>
        <hr>
        <textarea placehodler="请输入评论内容" maxlength="120" v-model="msg"></textarea>
        <mt-button  type="primary" size="large" @click="postComment" >点击发表</mt-button>
        <div class="cmt-list" v-for="(item, i) in comments" :key="item.add_time">
            <div class="cmt-item">
                <div class="cmt-title">
                    第{{i+1}}楼&nbsp;&nbsp;用户：{{item.user_name}}&nbsp;&nbsp;发表时间：{{item.add_time | dateFormat()}}
                </div>
                <!-- 用三元表达式解决数据为空的问题 -->
                <div class="cmt-body">{{item.content ==="" ? '此用户无话可说': item.content}}</div>
            </div>
        </div>
        <mt-button type="danger" size="large" @click="getMore">加载更多</mt-button>
    </div>
</template>

<script>
//mint-ui弹框
import {Toast} from 'mint-ui'

export default {
    data(){
        return {
            pageIndex:1,
            comments:[],//所有评论数据
            msg:""
        }
    },
    created(){
        this.getComment();
    },
    methods:{
        getComment(){
            // 'api/getcomments/:artid?pageindex=1'
            this.$http.get("api/getcomments/"+ this.id +"?pageindex="+ this.pageIndex).then(result=>{
                if(result.body.status===0){
                    // this.comments = result.body.message
                   //每当获取新评论数据的时候，不会被覆盖，采用数组拼接。
                   this.comments = this.comments.concat(result.body.message) 
                }else{
                    Toast('获取数据失败了')
                }
            })
        },
        getMore(){
            this.pageIndex ++;
            this.getComment()
        },
    postComment(){
        if(this.msg.trim().length ===0){
            return Toast('评论内容不能为空')
        }
        //emulateJSON  =true,可以在全局设置main.js，不用每次都设置
        this.$http.post('api/postcomment/'+this.$route.params.id,{
            content:this.msg.trim()
        }).then(function(result){
            if(result.body.status===0){
                //拼接出评论对象
                var cmt = {user_name:'匿名用户',add_time:Date.now(),content:this.msg.trim()}
                this.comments.unshift(cmt);
                this.msg=''
            }
        })
    } 
    },
    props:["id"]
}
</script>

<style lang="scss" scoped>
.cmt-container{
    h2{
        font-size: 18px;
    }

    .cmt-list{
        .cmt-item{
            .cmt-title{
                padding: 0 5px;
                line-height: 30px;
                font-size: 14px;
                background-color: #ccc;
            }
            .cmt-body{
                
                font-size: 14px;
                margin: 5px 0;
                padding: 0 5px;
            }
        }
    }
}
</style>